package com.zjlp.im.netty.client;

import com.zjlp.im.netty.handler.ChatMsgHandler;
import com.zjlp.im.netty.handler.DefaultClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroupFuture;
import io.netty.channel.group.ChannelGroupFutureListener;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.json.JsonObjectDecoder;
import io.netty.util.concurrent.Future;

public class EchoClient {


    private String user;
    private String guester;


    private final String SERVER_HOST = "127.0.0.1";

    private final int SERVER_PORT = 9779;

    public EchoClient(String user, String guester) {
        this.user = user;
        this.guester = guester;
    }

    public void initNettyClient() {
        // 客户端引导程序
        Bootstrap client = new Bootstrap();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        client.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
        client.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                // 客户端的逻辑
                /*pipeline.addLast(new JsonObjectDecoder());*/
                //pipeline.addLast("logger", new LoggingHandler());
                //传送消息需要加密 写消息经过此handler，
                //pipeline.addLast("encoder", new StringEncoder());
                pipeline.addLast("decoderJSON", new JsonObjectDecoder());
                //读消息需要经过此handler
                pipeline.addLast("handler", new DefaultClientHandler(user, guester));
                //添加聊天消息handler
                pipeline.addLast("decoder", new ChatMsgHandler(user, guester));

            }
        });
        // Start the client.
        try {
            Channel ch = client.connect(SERVER_HOST, SERVER_PORT).sync().channel();
            ChannelFuture cf = ch.closeFuture().sync();
            cf.addListener(new ChannelGroupFutureListener() {
                /**
                 * Invoked when the operation associated with the {@link Future} has been completed.
                 *
                 * @param future the source {@link Future} which called this callback
                 */
                @Override
                public void operationComplete(ChannelGroupFuture future) throws Exception {
                    System.out.println("我被执行了");
                }
            });
            cf.addListener(new ChannelFutureListener() {
                /**
                 * Invoked when the operation associated with the {@link Future} has been completed.
                 *
                 * @param future the source {@link Future} which called this callback
                 */
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        System.out.println("关闭链接成功,接下来发送json数据");
                    } else if (future.isCancelled()) {
                        System.out.println("连接被取消！！！");
                    }

                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        EchoClient client = new EchoClient("colin","joker");
        try {
            client.initNettyClient();
        } catch (Exception e) {
            System.out.println("初始化客户端出错了！！");
            e.printStackTrace();
        }
    }
}
